package com.car.util;

import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.HttpMethod; 
import org.apache.commons.httpclient.HttpStatus; 
import org.apache.commons.httpclient.URIException; 
import org.apache.commons.httpclient.methods.GetMethod; 
import org.apache.commons.httpclient.methods.PostMethod; 
import org.apache.commons.httpclient.params.HttpMethodParams; 
import org.apache.commons.httpclient.util.URIUtil; 
import org.apache.commons.lang.StringUtils; 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.json.JSONException;

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream;
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map; 

/**
 * @author LV
 * 2014年1月13日
 * 模拟Http的get和post请求
 */
public class HttpUtil { 
         private static Log log = LogFactory.getLog(HttpUtil.class); 
         
         
         
         public static String httpsGet(String url, String param ) throws IOException{
         	
             String result = "";
             BufferedReader in = null;
             String urlNameString = url + "?" + param;
             URL realUrl = new URL(urlNameString);
            
             // 打开和URL之间的连接
             URLConnection connection = realUrl.openConnection();
             // 设置通用的请求属性
             connection.setRequestProperty("accept", "*/*");
             connection.setRequestProperty("connection", "Keep-Alive");
             connection.setRequestProperty("user-agent",
                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
             
             // 建立实际的连接
             connection.connect();
             // 获取所有响应头字段
             Map<String, List<String>> map = connection.getHeaderFields();
             // 遍历所有的响应头字段
             for (String key : map.keySet()) {
                 System.out.println(key + "--->" + map.get(key));
             }
             // 定义 BufferedReader输入流来读取URL的响应
             in = new BufferedReader(new InputStreamReader(
                     connection.getInputStream()));
             String line;
             while ((line = in.readLine()) != null) {
                 result += line;
             }
             try {
                 if (in != null) {
                     in.close();
                 }
             } catch (Exception e2) {
                 e2.printStackTrace();
             }
             return result;
         }


         /**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */ 
         public static String doGet(String url, String queryString, String charset, boolean pretty) { 
                 StringBuffer response = new StringBuffer(); 
                 HttpClient client = new HttpClient(); 
                 HttpMethod method = new GetMethod(url); 
                 try { 
                         if (StringUtils.isNotBlank(queryString)) 
                                 //对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成为%式样的字符串 
                                method.setQueryString(URIUtil.encodeQuery(queryString)); 
                         client.executeMethod(method); 
                         if (method.getStatusCode() == HttpStatus.SC_OK) { 
                                 BufferedReader reader =  new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                                 String line; 
                                 while ((line = reader.readLine()) != null) { 
                                         if (pretty) 
                                                 response.append(line).append(System.getProperty("line.separator")); 
                                         else 
                                                 response.append(line); 
                                 } 
                                 reader.close(); 
                         } 
                 } catch (URIException e) { 
                         log.error("执行HTTP Get请求时，编码查询字符串“" + queryString + "”发生异常！", e); 
                 } catch (IOException e) { 
                         log.error("执行HTTP Get请求" + url + "时，发生异常！", e); 
                 } finally { 
                         method.releaseConnection(); 
                 } 
                 return response.toString(); 
         } 

         /** 
          * 执行一个HTTP POST请求，返回请求响应的HTML 
          * 
          * @param url         请求的URL地址 
         * @param params    请求的查询参数,可以为null 
          * @param charset 字符集 
         * @param pretty    是否美化 
         * @return 返回请求响应的HTML 
          */ 
         public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { 
                 StringBuffer response = new StringBuffer(); 
                 HttpClient client = new HttpClient(); 
                 HttpMethod method = new PostMethod(url); 
                 //设置Http Post数据 
                if (params !=  null) { 
                         HttpMethodParams p = new HttpMethodParams(); 
                         for (Map.Entry<String, String> entry : params.entrySet()) { 
                                 p.setParameter(entry.getKey(), entry.getValue()); 
                         } 
                         method.setParams(p); 
                 } 
                 try { 
                         client.executeMethod(method); 
                         if (method.getStatusCode() == HttpStatus.SC_OK) { 
                                 BufferedReader reader =  new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                                 String line; 
                                 while ((line = reader.readLine()) != null) { 
                                         if (pretty) 
                                                 response.append(line).append(System.getProperty("line.separator")); 
                                         else 
                                                 response.append(line); 
                                 } 
                                 reader.close(); 
                         } 
                 } catch (IOException e) { 
                         log.error("执行HTTP Post请求" + url + "时，发生异常！", e); 
                 } finally { 
                         method.releaseConnection(); 
                 } 
                 return response.toString(); 
         } 
         
         public static String post(String postUrl,String para) throws IOException {
     		URL url = new URL(postUrl);
     		URLConnection connection = url.openConnection();
     		connection.setDoOutput(true);
     		OutputStreamWriter out = new OutputStreamWriter(
     				connection.getOutputStream(), "utf-8");
     		out.write(para); // 向页面传递数据。post的关键所在！
     		out.flush();
     		out.close();
     		//发送成功，用以下方法就可以得到服务器的回应：
     		String sCurrentLine;
     		String sTotalString;
     		sCurrentLine = "";
     		sTotalString = "";
     		InputStream l_urlStream;
     		l_urlStream = connection.getInputStream();
     		BufferedReader l_reader = new BufferedReader(new InputStreamReader(
     				l_urlStream));
     		while ((sCurrentLine = l_reader.readLine()) != null) {
     			sTotalString += sCurrentLine + "\r\n";

     		}
     		return sTotalString;

     	}
     	

         public static void main(String[] args) throws JSONException {
//        	 String access_token = "fIRR4gxWtAv7jug5AqfUrEDy_NZxLA3UYKlLkP03KYmnt0t56dlZCBO-c7e4IS66n7Lya2u9zx5e9RQ2s5wRY-Lvot2c3-oN5pBuw9Z92kMg6ldQ91k_OV54f4TftG2qxLJ8uL2s3FupSA6-gB9adg";
//             String y = doGet("http://api.weixin.qq.com/cgi-bin/menu/get?access_token="+access_token, null, "utf-8", true);
//             JSONObject json = new JSONObject(y);
//             JSONObject menu = json.getJSONObject("menu");
//             JSONArray buttons = menu.getJSONArray("button");
//             int length = buttons.length();
//             for(int i=0;i<length;i++){
//            	 JSONObject button = (JSONObject) buttons.get(i);
//            	 String type = button.getString("type");
//            	 JSONArray sub_buttons = button.getJSONArray("sub_button");
//            	 int len = sub_buttons.length();
//            	 if(len>0){
//            		 for(int j=0;j<len;j++){
//            			 JSONObject sub_button = (JSONObject) sub_buttons.get(j);
//            			 String sub_type = sub_button.getString("type");
//            		 }
//            	 }
//            	 System.out.println(type);
//             }
//             System.out.println(y);
        	/* String at = "3dpDWJWs6W8j7On245paia8LxbEjrH8xx55nZiFzgFMB3V5CwAVcutGXyWMmrMf0vg6EACUtuwztQJECKT9SRrYXF_klF_N3V8m3sOfj1qTscvmqLj1zxNYyP3OGjAWSBVRlGwo32XvC89EqyiL3gQ";
//        	 String u = "http://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+at;
//        	 doGet(u, null, "utf-8", true);
        	 
        	 String url = "http://api.weixin.qq.com/cgi-bin/menu/create?access_token="+at;
        	 String params = "{\"button\": [{\"type\": \"click\", \"name\": \"今日歌曲\", \"key\": \"V1001_TODAY_MUSIC\"}, {\"type\": \"click\", \"name\": \"歌手简介\", \"key\": \"V1001_TODAY_SINGER\"}, {\"name\": \"菜单\", \"sub_button\": [{\"type\": \"view\", \"name\": \"搜索\", \"url\": \"http://www.soso.com/\"}, {\"type\": \"view\", \"name\": \"视频\", \"url\": \"http://v.qq.com/\"}, {\"type\": \"click\",\"name\": \"赞一下我们\", \"key\": \"V1001_GOOD\"}]}]}";
			 try {
				String s= post(url, params);
				System.out.println(s);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
        	 String name ="小雨";
//        	 try {
//				name =  URLEncoder.encode(name, "utf-8");
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
        	 
        	 
        	 String url = "http://yueqiao.org/web/teaweb/studentDetail.json?name="+name;
			 String student;
			try {
				student = HttpUtil.post(url, "");
				System.out.println(student);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
         } 
 }